﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using System.IO;

namespace NMigrate
{

	public class CsFileHandler : FileHandler
	{
		#region FileHandler Members

		public override string Extension
		{
			get
			{
				return "cs";
			}
		}

		public override void Execute(System.IO.FileInfo file, Configuration args)
		{
			Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
			var options = new System.CodeDom.Compiler.CompilerParameters();
			options.ReferencedAssemblies.AddRange(GetAssemblies());
			options.GenerateInMemory = false; //default
			options.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
			options.IncludeDebugInformation = true;
			var result = codeProvider.CompileAssemblyFromFile(options, file.FullName);
			if(result.Errors.HasErrors)
			{
				throw new Exception(ToString(result.Errors));
			}
			var generatedType = result.CompiledAssembly.GetTypes().Single(t => typeof(IExecutable).IsAssignableFrom(t));
			var exec = (IExecutable)Activator.CreateInstance(generatedType);
			exec.Execute(args);
		}

		private string ToString(CompilerErrorCollection compilerErrorCollection)
		{
			return compilerErrorCollection.OfType<CompilerError>().Select(s => s.ToString() + "\r\n").Aggregate((a,b) => a + b);
		}

		private string[] GetAssemblies()
		{
			return AppDomain.CurrentDomain.GetAssemblies().Where(a=> !a.IsDynamic).Select(a => a.Location).ToArray();
		}

		#endregion

		#region FileHandler Members


		public override bool IsTemplated(FileInfo file)
		{
			return false;
		}

		#endregion
	}
}
